<script setup lang='ts'>
import { useSendSms } from '@fl/api/mall-api'
import { downTpl, useCheckCode, useGetDetail, useGetOrgTypeDict, useGetQcc, useMallGetAllSupplierTree, useProfileSave } from '@fl/api/man-api/jc-authentication'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { isUnifyTheSCC } from '@fl/utils/validate'
import { cloneDeep } from 'lodash-es'
import { computed, getCurrentInstance, ref } from 'vue'

import { AUDIT_STATUS_DICT, cascaderOptions } from './constant'
import { useRule } from './use-rule'
import { useStep } from './use-step'

const instance = getCurrentInstance()
const { rules } = useRule(instance)

const { stepMove } = useStep()
const searchRef = ref()
const fileType = '.rar,.zip,.doc,.docx,.pdf,.jpg,.jpeg,.png,.xlsx'
const isSubmit = ref<number>(0)
const state = {
    attachmentsAuthorizationLetterList: [], // 授权函附件列表
    businessLicenseAttachmentsList: [], // 营业执照附件列表
    captcha: '', // 验证码
    companyName: '',
    contactAddress: '',
    contactCardNo: '',
    contactEmail: '',
    contactMobile: '',
    contactName: '',
    enterpriseSecondType: '', // 企业二级类型
    enterpriseType: '', // 企业类型
    isDraft: 1, // 是否草稿 0: 不是, 1: 是
    legalRepresentative: '',
    logo: '',
    projectPerformanceList: [],
    qualificationDocumentList: [],
    registeredAddress: '',
    registeredMobile: '',
    supplyCat: [],
    unifiedSocialCreditCode: '', // 信用代码
}

const isFirstRending = ref(true)

const form = ref(cloneDeep(state))

const { data: detail, isSuccess } = useGetDetail()

const { data: supplierTree } = useMallGetAllSupplierTree()

const { data: dict } = useGetOrgTypeDict()

const getUscc = computed(() => {
    return form.value.unifiedSocialCreditCode
})
const { isPending: QccPending, mutate: QccMutate } = useGetQcc()
// 查询企业信息 回显
async function doAuthen() {
    if (!getUscc.value) {
        ElMessage.error('请输入统一社会信用代码')
        return
    }
    if (!isUnifyTheSCC(getUscc.value)) {
        ElMessage.error('请输入正确的统一社会信用代码')
        return
    }
    QccMutate(getUscc, {
        onSuccess: (data: any) => {
            if (data) {
                // 查询企业信息回显
                const { Address, CreditCode, Name, OperName } = data
                form.value.registeredAddress = Address
                form.value.legalRepresentative = OperName
                form.value.companyName = Name
                form.value.unifiedSocialCreditCode = CreditCode
            }
        },
    })
}

const group: any = [
    {
        columns: [
            {
                fieldProps: {
                    onChange: (_val: any) => {
                        // 重置 供应商/采购商类型
                        form.value.enterpriseSecondType = ''
                        form.value.supplyCat = []
                    },
                },
                label: '企业类型',
                options: computed(() => {
                    return dict.value
                }),
                prop: 'enterpriseType',
                valueType: 'radio',
            },
            {
                label: computed(() => {
                    return form.value.enterpriseType === '0' ? `采购商类型` : `供应商类型`
                }),
                options: computed(() => {
                    if (!dict.value) {
                        return []
                    }

                    return dict.value.find((v: any) => v.value === `${form.value.enterpriseType}`)?.children ?? []
                }),
                prop: 'enterpriseSecondType',
                valueType: 'select',
                width: 120,
            },
            {
                fieldProps: {
                    props: {
                        multiple: true,
                    },
                    showAllLevels: false,
                },
                hideInForm: computed(() => !(form.value.enterpriseType === '1')),
                label: '供应商类别',
                options: computed(() => {
                    return supplierTree.value || []
                }),
                prop: 'supplyCat',
                valueType: 'cascader',
                width: 120,
            },
        ],
        title: '机构类型',
    },
    {
        columns: [
            {
                colProps: {
                    span: 8,
                },
                label: '统一社会信用代码',
                prop: 'unifiedSocialCreditCode',
            },
            {
                fieldProps: {
                    disabled: true,
                },
                label: '公司名称',
                prop: 'companyName',
            },
            {
                fieldProps: {
                    disabled: true,
                },
                label: '法定代表人',
                prop: 'legalRepresentative',
            },
            {
                label: '注册电话',
                prop: 'registeredMobile',
            },
            {
                colProps: {
                    span: 16,
                },
                label: '企业LOGO',
                prop: 'logo',
            },
            {
                colProps: {
                    span: 24,
                },
                fieldProps: {
                    disabled: true,
                },
                label: '注册地址',
                prop: 'registeredAddress',
            },

        ],
        title: '企业信息',
    },
    {
        columns: [
            {
                label: '姓名',
                prop: 'contactName',
            },
            {
                label: '邮箱',
                prop: 'contactEmail',
            },
            {
                label: '联系电话',
                prop: 'contactMobile',
            },
            {
                label: '联系人身份证号',
                prop: 'contactCardNo',
            },
            {
                label: '验证码',
                prop: 'captcha',
            },
        ],
        title: '认证联系人信息',
    },
    {
        columns: [
            {
                label: '营业执照附件',
                prop: 'businessLicenseAttachmentsList',
            },
            {
                label: '授权函',
                prop: 'attachmentsAuthorizationLetterList',
            },
            {
                label: '资质文件',
                prop: 'qualificationDocumentList',
            },
            {

                label: '项目业绩',
                prop: 'projectPerformanceList',
            },
        ],
        title: '附件（支持扩展名：.rar .zip .doc .docx .pdf .jpg .jpeg .png .xlsx等，单个附件最大支持20M，资质文件和项目业绩最多支持20个文件上传）',
    },
]

const countdown = ref(0)
const isDown = computed(() => {
    return unref(countdown) > 0
})

const { isPending: isPendingSendSms, mutate: mutateSendSms } = useSendSms()
function getCode() {
    const mobile = form.value.contactMobile

    if (!mobile) {
        ElMessage.error('请输入联系电话')
        return
    }

    mutateSendSms({ mobile }, {
        onSuccess: () => {
            ElMessage.success('验证码已发送，请注意查收')
            countdown.value = 60 // 时效五分钟

            const interval = setInterval(() => {
                countdown.value = countdown.value - 1
                if (unref(countdown) === 0)
                    clearInterval(interval)
            }, 1000)
        },
    })
}

const { isPending, mutate } = useProfileSave()
function doSubmit(isSkip: boolean) {
    const target = cloneDeep(form.value)
    const businessLicenseAttachmentsList = target.businessLicenseAttachmentsList.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    })
    const attachmentsAuthorizationLetterList = target.attachmentsAuthorizationLetterList.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    })
    const qualificationDocumentList = target.qualificationDocumentList?.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    }) || []
    const projectPerformanceList = target.projectPerformanceList?.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    }) || []
    const supplyCat = JSON.stringify(target.supplyCat)
    Reflect.deleteProperty(target, 'captcha')
    const formData = { ...target, attachmentsAuthorizationLetterList, businessLicenseAttachmentsList, isDraft: 1, projectPerformanceList, qualificationDocumentList, supplyCat }
    console.log(formData)
    mutate(formData, {
        onSuccess: () => {
            // 下一步 调转
            if (isSkip) {
                window.sessionStorage.setItem('IS_SUBMIT', JSON.stringify(isSubmit.value))
                stepMove({ step: 2 })
            }
            else { // 保存草稿 不做跳转
                ElMessage.success('保存成功')
            }
        },
    })
}

const { mutateAsync: checkCodeMutate } = useCheckCode()

// 保存草稿 不做校验
async function saveDraft() {
    doSubmit(false)
}

// 下一步 校验通过 保存草稿
async function doNext() {
    // 1.表单校验
    const isVal = await searchRef.value.formInstance.handleSubmit()

    if (!isVal)
        return

    // 3.校验手机验证码
    const captcha = form.value.captcha
    const phone = form.value.contactMobile
    if ((detail.value?.authType === null || detail.value?.contactMobile !== form.value.contactMobile)) {
        isSubmit.value = 1
        checkCodeMutate({ captcha, phone }, {
            onError: () => {
                isSubmit.value = 0
            },
            onSuccess: () => {
                doSubmit(true)
            },
        })
    }
    else {
        doSubmit(true)
    }
}

// 上一步 缓存当前修改
function upStep() {
    window.sessionStorage.setItem('IS_SUBMIT', JSON.stringify(isSubmit.value))
    window.sessionStorage.setItem('PROFILE_FORM_DATA', JSON.stringify(form.value))
    stepMove({ form: '1', step: 0 })
}

// 拉取缓存
function getCache() {
    // isSubmit.value = JSON.parse(window.sessionStorage.getItem('IS_SUBMIT') || '0') || 0
    // const str = window.sessionStorage.getItem('PROFILE_FORM_DATA')
    // if (str) {
    //     return JSON.parse(str)
    // }
    return {}
}

async function init(detail) {
    if (detail) {
        const target = {
            ...cloneDeep(detail),
            // ...getCache(),
        }

        // 审核不通过 重新认证 拉取历史数据回显
        if (target.auditStatus === AUDIT_STATUS_DICT.FORBIDDEN) {
            // 去掉认证方式 审核状态
            Reflect.deleteProperty(target, 'legalPersonAuth')
            Reflect.deleteProperty(target, 'auditStatus')
        }

        const businessLicenseAttachmentsList = target.businessLicenseAttachmentsList.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        })
        const attachmentsAuthorizationLetterList = target.attachmentsAuthorizationLetterList.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        })
        const qualificationDocumentList = target.qualificationDocumentList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const projectPerformanceList = target.projectPerformanceList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const supplyCat = target.supplyCat ? JSON.parse(target.supplyCat) : []
        form.value = {
            ...form.value,
            ...target,
            attachmentsAuthorizationLetterList,
            businessLicenseAttachmentsList,
            enterpriseSecondType: `${target.enterpriseSecondType}`,
            enterpriseType: `${target.enterpriseType}`,
            logo: target.logo || '',
            projectPerformanceList,
            qualificationDocumentList,
            supplyCat,
        }
    }
    else {
        form.value = {
            ...form.value,
            ...getCache(),
        }
    }
}

function validatorCpt(rule, value, callback) {
    const reg = /^\d{1,8}$/
    if (!reg.test(value))
        callback(new Error('请输入验证码'))
    else callback()
}

watchEffect(() => {
    if (detail.value?.authType !== null && detail.value?.contactMobile === form.value.contactMobile) {
        rules.captcha = [{
            required: false,
            trigger: 'blur',
        }]
    }
    else {
        rules.captcha = [{
            required: true,
            trigger: 'blur',
            validator: validatorCpt,
        }]
    }
})

watchEffect(() => {
    if (isSuccess.value && isFirstRending.value) {
        init(detail.value)
        isFirstRending.value = false
    }
})

// 更换信用代码 清空关联信息
function codeChange(_val: any) {
    form.value.registeredAddress = ''
    form.value.legalRepresentative = ''
    form.value.companyName = ''
}

defineExpose({
    form,
})
</script>

<template>
    <div class="w-full">
        <SearchForm ref="searchRef"
                    v-model="form"
                    :has-footer="false"
                    :group="group"
                    :rules="rules"
                    label-position="top"
        >
            <template #plus-field-unifiedSocialCreditCode>
                <el-row class="w-full">
                    <el-col :span="18">
                        <el-input v-model="form.unifiedSocialCreditCode"
                                  @change="codeChange"
                        />
                    </el-col>

                    <el-col :span="4">
                        <el-button v-loading="QccPending"
                                   type="primary"
                                   class="ml-10"
                                   @click="doAuthen"
                        >
                            企业认证
                        </el-button>
                    </el-col>
                </el-row>
            </template>

            <template #plus-field-captcha>
                <div class="relative w-full">
                    <el-input v-model="form.captcha"
                              v-loading="isPendingSendSms"
                              style="width: 399px;"
                    />

                    <span v-if="isDown"
                          class="text-16 c-#DA0004 absolute cursor-pointer right-12 top-2"
                    >{{ countdown
                    }}秒后重发</span>

                    <span v-else
                          class="text-16 c-#DA0004 absolute cursor-pointer right-12 top-2"
                          @click="getCode"
                    >获取验证码</span>
                </div>
            </template>

            <template #plus-field-logo>
                <FlUpload :key="String(isFirstRending)"
                          v-model="form.logo"
                          :limit="1"
                          :file-size="5"
                          accept=".jpg,.jpeg,.png"
                          tips="鼠标移入图标即可修改,支持扩展名: .jpg,.jpeg,.png,所选图片大小不能超过 5 MB,最多上传 1 个文件"
                />
            </template>

            <template #plus-field-businessLicenseAttachmentsList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="String(isFirstRending)"
                              v-model="form.businessLicenseAttachmentsList"
                              list-type="text"
                              :limit="1"
                              :file-size="20"
                              :accept="fileType"
                    />

                    <div class="text-14 c-#86909C cursor-pointer">
                        最多上传一张
                    </div>
                </div>
            </template>

            <template #plus-field-attachmentsAuthorizationLetterList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="String(isFirstRending)"
                              v-model="form.attachmentsAuthorizationLetterList"
                              list-type="text"
                              :limit="1"
                              :file-size="20"
                              :accept="fileType"
                    />

                    <div class="text-14 c-#86909C cursor-pointer"
                         @click="downTpl('授权函模板')"
                    >
                        <span class="c-#EA0000">下载</span>《授权函模板》
                    </div>
                </div>
            </template>

            <template #plus-field-qualificationDocumentList>
                <FlUpload :key="String(isFirstRending)"
                          v-model="form.qualificationDocumentList"
                          list-type="text"
                          :limit="20"
                          :file-size="20"
                          :accept="fileType"
                />
            </template>

            <template #plus-field-projectPerformanceList>
                <FlUpload :key="String(isFirstRending)"
                          v-model="form.projectPerformanceList"
                          list-type="text"
                          :limit="20"
                          :file-size="20"
                          :accept="fileType"
                />
            </template>
        </SearchForm>

        <div class="text-center">
            <ElButton v-loading.fullscreen.lock="isPending"
                      class="mb-30 mt-20"
                      @click="saveDraft"
            >
                保存草稿
            </ElButton>

            <ElButton class="mb-30 mt-20"
                      @click="upStep"
            >
                上一步
            </ElButton>

            <ElButton class="mb-30 mt-20"
                      type="primary"
                      @click="doNext"
            >
                下一步
            </ElButton>
        </div>
    </div>
</template>

<style lang="less" scoped>

</style>
